<template>
    <div class="upload-list"><!-- v-if='!!imageHost'-->
        <div class="demo-upload-list" v-for="item in uploadList">
            <template v-if="item.status === 'finished'">
                <img-path class='w-100' :src='item.name' :w='100' :h='100'></img-path>
                <div class="demo-upload-list-cover">
                    <btn-confirm  p-message='你确定要删除此图片吗？' @on-change='handleRemove(item)'>
                        <Icon type="ios-trash-outline"></Icon>
                    </btn-confirm>
                </div>
            </template>
            <template v-else>
                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template>
        </div>
        <Upload
                v-show='isAddBoxShow'
                style='display:inline-block'
                ref="upload"
                :default-file-list="defaultList"
                :show-upload-list="false"
                :multiple='pMultiple'
                :data="paramsData"
                :before-upload="beforeUpload"
                :on-progress="onProgress"
                :on-success="onSuccess"
                :on-error="onError"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                type="drag"
                :format="['jpg','jpeg','png']"
                :max-size="this.pSize"
                :action="imageHost">
            <template v-if='!!$slots.default'>
                <slot></slot>
            </template>
            <template v-else>
                <div style="width: 100px;height:100px;line-height: 100px;">
                    <Icon type="camera" size="20"></Icon>
                </div>
            </template>
        </Upload>
    </div>
</template>
<script>
    import Promise from 'promise'
    import serOss from 'serves/api-oss'
    import {img_whq} from 'filters/index'
    import {isArray} from '../../utils/index'
    import serConfig from '../../api-config'
    export default {
        name:"ImgUpload",
        props:{
            pData:{
                type:[Array,String]
            },
            pMultiple:{
                type:Boolean,
                default:false
            },
            pDir:{
                type:String,
                required:true
            },
            pSize:{
                type:Number,
                default:3072
            },
            pCount:{
                type:Number,
                default:1
            },
            pReplace:{
                type:Boolean,
                default:true
            }
        },
        data () {
            return {
                defaultList:[],
                paramsData:{},
                uploadList:[],
                imageHost:'',
                imgName:false,
                visible:false,
                progressNum:0,
            }
        },
        computed:{
            isMultiple(){
                return isArray(this.pData);
            },
            isAddBoxShow(){
                if(this.pCount == this.uploadList.length){
                    return false;
                }else {
                    return true;
                }
            }
        },
        mounted (){
            this.init(this.pData);
        },
        methods: {
            init(data){
                let c = [];
                if(this.isMultiple){
                    c = data.map((v,i)=>({name:v}));
                }else {
                    if(data){
                        c = [{name:data}];
                    }
                }
                this.$set(this,'defaultList',c);
                this.listInit();
            },
            listInit(){
                this.$nextTick(() => {
                    if(this.$refs.upload){
                        this.$set(this,'uploadList',this.$refs.upload.fileList);
                    }
                });
            },
            async ossInit(){
                let res = await serOss.api({dir:this.pDir});
                this.$set(this, 'imageHost', res.host);
                this.paramsData = res.data;
                return true;
            },
            async beforeUpload(data){
                let check;
                if(this.pCount!=-1){
                    check = this.uploadList.length < this.pCount;
                }else {
                    check = true;
                }
                if (!check) {
                    this.$Notice.warning({
                        title: '最多只能上传 '+this.pCount+' 张图片。'
                    });
                    return false
                }else {
                    await this.ossInit();
                    return new Promise((resolve)=>{
                        resolve(new File([data],this.pDir+'_photo_'+serOss.name() + data.name.match(/\.\w*?$/)[0],{type:data.type,size:data.size}))
                    });
                }
            },
            handleFormatError (file) {
                this.$Notice.warning({
                    title: '文件格式不正确',
                    desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg、jpeg 或 png 格式的图片。'
                });
            },
            handleMaxSize (file) {
                this.$Notice.warning({
                    title: '超出文件大小限制',
                    desc: '文件 ' + file.name + ' 太大，不能超过 '+this.pSize+'KB。'
                });
            },
            onProgress(event, file, fileList){
                if (event.total > 0) {
                    this.progressNum = parseInt(event.loaded / event.total * 100);
                }
            },
            onSuccess(response, file, fileList){
                /*TODO 后端oss配置问题，暂时去掉状态判断*/
                this.$emit('on-success',{dir:this.dir,name:file.name,files:fileList});
                /*if(response.Status=='Ok'){
                    this.$emit('on-success',{dir:this.dir,name:file.name,files:fileList});
                }else {
                    this.$Notice.warning({
                        title: '上传错误',
                        desc: '文件上传错误，请重试。'
                    });
                }*/
            },
            onError(err){
                this.$Notice.warning({
                    title: '上传错误',
                    desc: '文件上传错误，请重试。'
                });
            },
            handleRemove (file) {
                // 从 upload 实例删除数据
                const fileList = this.$refs.upload.fileList;
                fileList.forEach((x,y)=>{
                    if(file.name==x.name){
                        fileList.splice(y,1);
                        this.listInit();
                        this.$emit('on-delete',{dir:this.dir,name:file.name,index:y,files:fileList});
                    }
                });
            },
            handleClear (all) {
                if(all){
                    this.$refs.upload.clearFiles();
                }
            },
        },
        watch:{
            pData(newValue){
                this.init(newValue);
            }
        }
    }
</script>
<style>
    .upload-list{
        display:inline-block;
    }
    .demo-upload-list{
        width: 100px;
        height: 100px;
        display: inline-block;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 4px;
    }
    .demo-upload-list img{
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        right: 0;
        line-height: 0;
        padding:2px 10px;
        border-radius: 4px;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: inline-block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 24px;
        font-weight: bold;
        cursor: pointer;
    }
</style>
